
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using SqlSugar;
using System.Threading;
using Util;

namespace API.Controllers
{
    public class OfficeMaterialsController : BaseController
    {
        Repository<tOfficeMaterials> _OfficeMaterials;
        Repository<tOfficeMaterialSupplier> _OfficeMaterialSupplier;
        readonly IMapper _mapper;
        public OfficeMaterialsController(Repository<tOfficeMaterials> OfficeMaterials, IMapper mapper, Repository<tOfficeMaterialSupplier> OfficeMaterialSupplier)
        {
            _OfficeMaterials = OfficeMaterials;
            _mapper = mapper;
            _OfficeMaterialSupplier = OfficeMaterialSupplier;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveOfficeMaterialsInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tOfficeMaterials>(dto);
                InitEntity(model);
                await _OfficeMaterials.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<OfficeMaterialsOutput>>> GetList([FromBody] OfficeMaterialsListInput dto)
        {
            ResultMsg<List<OfficeMaterialsOutput>> result = new ResultMsg<List<OfficeMaterialsOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tOfficeMaterials>();
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    exp.And(x => x.FName.Contains(dto.Name));
                }
                var list = (await _OfficeMaterials.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var OfficeMaterialsOutputs = _mapper.Map<List<OfficeMaterialsOutput>>(list);
                return result.Success(OfficeMaterialsOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<OfficeMaterialsOutput>> GetTheOne(string id)
        {
            ResultMsg<OfficeMaterialsOutput> result = new ResultMsg<OfficeMaterialsOutput>();
            try
            {
                var model = await _OfficeMaterials.GetByIdAsync(id);
                var dao = _mapper.Map<OfficeMaterialsOutput>(model);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _OfficeMaterials.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 添加/更改物料供应商
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> SaveSup(SaveOfficeMaterialSupplierInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tOfficeMaterialSupplier>(dto);
                InitEntity(model);
                await _OfficeMaterialSupplier.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--SaveSup:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<OfficeMaterialSupplierOutput>>> GetSupplierList([FromBody] OfficeMaterialSupplierListInput dto)
        {
            ResultMsg<List<OfficeMaterialSupplierOutput>> result = new ResultMsg<List<OfficeMaterialSupplierOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tOfficeMaterialSupplier>();
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    exp.And(x => x.FName.Contains(dto.Name));
                }
                var list = (await _OfficeMaterialSupplier.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var OfficeMaterialSupplierOutputs = _mapper.Map<List<OfficeMaterialSupplierOutput>>(list);
                foreach (var item in OfficeMaterialSupplierOutputs)
                {
                    var materials = await _OfficeMaterials.GetListAsync(x => x.FSupplierId == item.Id);
                    item.materials=_mapper.Map<List<OfficeMaterialsOutput>>(materials);
                }
                return result.Success(OfficeMaterialSupplierOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--GetSupplierList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除办公室物料供应商
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> DelSupplier(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _OfficeMaterialSupplier.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--DelSupplier:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 上传物料图片
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> UploadFiles([FromForm] IFormCollection formCollection)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            List<string> list = new List<string>();
            try
            {
                int materialId = Convert.ToInt32(formCollection["materialId"]);
                FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
                if (fileCollection != null && fileCollection.Count > 0)
                {
                    list = UploadOperate.UploadSteam(fileCollection, "file/material/");
                }
                string photo = list[0];
                if (materialId != 0)
                {
                    var model = await _OfficeMaterials.GetByIdAsync(materialId);
                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "material", model.FPhoto); //根据你的实际情况来组合文件路径  

                    if (System.IO.File.Exists(filePath))
                    {
                        try
                        {
                            System.IO.File.Delete(filePath);
                        }
                        catch (Exception ex)
                        {
                            Util.NLOG.LogHelper.Error("OfficeMaterialsController--UploadFiles:删除文件时出错:" + ex.ToString());
                        }
                    }
                }
                return result.Success(photo);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("OfficeMaterialsController--UploadFiles:" + ex.ToString());
                return result.Exception();
            }
        }
    }
}
